package com.pig4cloud.pig.module.controller.promoter;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.promoter.Promoter;
import com.pig4cloud.pig.module.api.entity.promoter.PromoterSettlement;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.promoter.IPromoterService;
import com.pig4cloud.pig.module.service.promoter.IPromoterSettlementService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 推广员 结算单Controller
 *
 * @author ruoyi
 * @date 2022-11-11
 */
@Validated
@Api(value = "推广员 结算单控制器", tags = {"推广员 结算单管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/promoterSettlement")
public class PromoterSettlementController {

    private final IPromoterSettlementService promoterSettlementService;
    private final IPromoterService promoterService;
    private final IWxUserService wxUserService;
	private final IWxTemplateService wxTemplateService;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;
    /**
     * 查询推广员 结算单列表
     */
    @ApiOperation("查询推广员 结算单列表")
    @PreAuthorize("@pms.hasPermission('module:promoterSettlement:list')")
    @GetMapping("/list")
    public TableDataInfo<PromoterSettlement> list(@Validated PromoterSettlement promoterSettlement) {
        QueryWrapper<PromoterSettlement> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(promoterSettlement.getBeginDate())){
            qw.between("create_time", promoterSettlement.getBeginDate() + " 00:00:00",promoterSettlement.getEndDate() + " 23:59:59");
        }

        qw.orderByDesc("create_time");
        TableDataInfo<PromoterSettlement> td = PageUtils.buildDataInfo(promoterSettlementService.page(PageUtils.buildPage(),qw));
        List<PromoterSettlement> list = td.getData();
        for(PromoterSettlement list1:list){
            if (list1.getPromoterId()!=null){
                Promoter promoter = promoterService.findById(list1.getPromoterId());
                if(promoter != null){
                	if(StrUtil.isNotEmpty(promoter.getName())){
						list1.setPromoterName(EmojiParser.parseToUnicode(promoter.getName()));
					}
					if (promoter.getWxUserId()!=null){
						WxUser wxUser = wxUserService.findById(promoter.getWxUserId());
						if(wxUser!=null){
							list1.setFaceUrl(wxUser.getFaceUrl());
							if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0){
								list1.setFaceUrl(imgUrl + wxUser.getFaceUrl());
							}
						}
					}
				}
            }

        }
        return td;
    }

    /**
     * 导出推广员 结算单列表
     */
    @ApiOperation("导出推广员 结算单列表")
    @PreAuthorize("@pms.hasPermission('module:promoterSettlement:export')")
    @SysLog("推广员 结算单")
    @GetMapping("/export")
    public List export(@Validated PromoterSettlement promoterSettlement) {
        List<PromoterSettlement> list = promoterSettlementService.list();
        // ExcelUtil<PromoterSettlement> util = new // ExcelUtil<PromoterSettlement>(PromoterSettlement.class);
        return  list;// util.exportExcel(list, "推广员 结算单");
    }

    /**
     * 获取推广员 结算单详细信息
     */
    @ApiOperation("获取推广员 结算单详细信息")
    @PreAuthorize("@pms.hasPermission('module:promoterSettlement:query')")
    @GetMapping("/{id}")
    public R<PromoterSettlement> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        PromoterSettlement promoterSettlement = promoterSettlementService.getById(id);
        return R.ok(promoterSettlement);
    }

    /**
     * 新增推广员 结算单
     */
    @ApiOperation("新增推广员 结算单")
    @PreAuthorize("@pms.hasPermission('module:promoterSettlement:add')")
    @SysLog("推广员 结算单")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody PromoterSettlement promoterSettlement) {
        return R.okByRow(promoterSettlementService.save(promoterSettlement) ? 1 : 0);
    }

    /**
     * 修改推广员 结算单
     */
    @ApiOperation("修改推广员 结算单")
    @PreAuthorize("@pms.hasPermission('module:promoterSettlement:edit')")
    @SysLog("推广员 结算单")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody PromoterSettlement promoterSettlement) {
        PigUser sysUser = SecurityUtils.getUser();
        if(promoterSettlement.getState() == 0){
            promoterSettlement.setCheckSysUserId(sysUser.getId());
            promoterSettlement.setCheckSysUserName(sysUser.getName());
            promoterSettlement.setCheckTime(new Date());
        }else if(promoterSettlement.getState() == 1){
            promoterSettlement.setSubmitSysUserId(sysUser.getId());
            promoterSettlement.setSubmitUserName(sysUser.getName());
            promoterSettlement.setSubmitTime(new Date());
        }

		boolean bl = false;
		if(promoterSettlement.getState() == 1){
			Map<String,Object> map = promoterSettlementService.checkRecord(promoterSettlement);
			if(map.containsKey("result_code")){
				if(map.get("result_code").equals("SUCCESS")){
					return R.okByRow(1);
				} else {
					return R.failed(map.get("err_code_des").toString());
				}
			}
			return R.okByRow(0);
		}else{
			if(promoterSettlement.getState() == 0){
				promoterSettlement.setState(1);
			}
			bl = promoterSettlementService.updateById(promoterSettlement);
			if(bl){
				if(promoterSettlement.getState() == 1){
					//发送推送给财务部门，通知结算
					wxTemplateService.sendWxMsgPromoterSettleSubmit(promoterSettlement,promoterSettlement.getPayMoney().doubleValue());
				}
			}
		}

        return R.okByRow(promoterSettlementService.updateById(promoterSettlement) ? 1 : 0);
    }


    /**
     * 删除推广员 结算单
     */
    @ApiOperation("删除推广员 结算单")
    @PreAuthorize("@pms.hasPermission('module:promoterSettlement:remove')")
    @SysLog("推广员 结算单")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(promoterSettlementService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
